import { Message } from "@arco-design/web-vue";
import { defineStore } from "pinia";
import LocalCache from "@/utils/storage";
import router from "@/router/index";
import type { userStoreType } from "./index.d";
import { logOutApi, userInfoApi } from "@/api";
import { MsgEnum } from "@/enum/msg";
import { parseToken } from "@/utils/parseToken";

const roleName = ["-", "管理员", "普通用户", "游客"];

export const userStoreModel = defineStore("userStore", {
  state: (): userStoreType => {
    return {
      userInfo: {
        userID: 0,
        username: "",
        role: 0,
        token: "",
      },
    };
  },
  actions: {
    saveUserInfo(token: string) {
      this.userInfo.token = token;
      const payLoad = parseToken(token);
      this.userInfo.role = payLoad.role;
      this.userInfo.userID = payLoad.userID;

      userInfoApi()
        .then((res) => {
          this.userInfo.role = res.data.role;
          this.userInfo.userID = res.data.userID;
          this.userInfo.username = res.data.username;
          LocalCache.set("userInfo", JSON.stringify(this.userInfo));
        })
        .catch((err) => {
          Message.error(MsgEnum.fail);
        });
    },

    loadUserinfo() {
      const userInfo = LocalCache.get("userInfo");
      if (!userInfo) {
        return;
      }
      try {
        this.userInfo = JSON.parse(userInfo);
      } catch (err) {
        console.log(err);
        return;
      }
      const payLoad = parseToken(this.userInfo.token);
      const nowTime = new Date().getTime(); //毫秒
      console.log("解析的token：", payLoad);

      if (payLoad.exp * 1000 - nowTime <= 0) {
        //exp秒
        Message.error("登录过期，请重新登录");
        LocalCache.delete("userInfo");
        router.push({ name: "Login" });
        return;
      }
    },
    async logOut() {
      try {
        // const res = await logOutApi();//TODO
        LocalCache.delete("userInfo");
        this.userInfo = {
          userID: 0,
          username: "",
          role: 0,
          token: "",
        };
        Message.success(MsgEnum.logoutSuccess);
        router.push({ name: "Login" });
      } catch (err) {
        console.log(err);
      }
    },
  },
  getters: {
    isLogin(state) {
      return state.userInfo.token !== "";
    },
  },
});
